﻿using AutoMapper;
using MediatR;
using Production.CommonLib.Models;
using Production.DomainLib.AggregatesModel.ProductionResourceAggregate;
using Swimj.CommonLib.Base;

namespace Production.ApplicationLib.Command
{
    public class CreateProductionResourceCommand : ProductionResourceEditRequestDto, IRequest<Result<ProductionResourceInfoResponseDto>>
    {
    }

    public class CreateProductionResourceCommandHandler : IRequestHandler<CreateProductionResourceCommand,
        Result<ProductionResourceInfoResponseDto>>
    {
        private readonly IProductionResourceRepository _productionResourceRepository;
        private readonly IMapper _mapper;

        public CreateProductionResourceCommandHandler(IProductionResourceRepository productionResourceRepository,
            IMapper mapper)
        {
            _productionResourceRepository = productionResourceRepository;
            _mapper = mapper;
        }

        public async Task<Result<ProductionResourceInfoResponseDto>> Handle(CreateProductionResourceCommand request,
            CancellationToken cancellationToken)
        {
            var productionResource = new ProductionResource(request.Code, request.Name, request.IsResourceGroup, request.IsStopGroup,
                request.ResourceCategory, request.MaxLoad, request.PipelineInterval, request.IdleTime,
                request.Quantity, request.Sort, request.Description);

            _productionResourceRepository.Add(productionResource);

            await _productionResourceRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
            
            return await Result<ProductionResourceInfoResponseDto>.SuccessAsync(
                _mapper.Map<ProductionResourceInfoResponseDto>(productionResource));

        }
    }
}